package JasPerl::JspWriter;

use strict;
use warnings;

use constant {
    NO_BUFFER        => 0,
    DEFAULT_BUFFER   => -1,
    UNBOUNDED_BUFFER => -2
};

sub from {
    my ($class, $from) = @_;
    return $from if $from->isa($class);
    return JasPerl::UnbufferedWriter->new($from);
}

sub get_buffer_size {
    return NO_BUFFER;
}

sub get_remaining {
    return NO_BUFFER;
}

sub is_auto_flush {
    # default implementation is not auto-flush
}

sub clear {
    JasPerl::IOException->throw("cannot clear $_[0]");
}

sub flush {
    JasPerl::IOException->throw("cannot flush $_[0]");
}

sub print {
    my $self = shift;

    foreach my $arg (@_) {
        $self->write(defined $arg ? $arg : 'null');
    }
}

sub println {
    shift->print(@_, "\n");
}

sub write {
    die ref $_[0], "::write not implemented";
}

package # hide from PAUSE
    JasPerl::UnbufferedWriter;

use parent qw(-norequire JasPerl::JspWriter);

use IO::Handle;

sub new {
    my ($class, $out) = @_;
    bless \$out, $class;
}

sub flush {
    ${+shift}->flush() or JasPerl::IOException->throw($!);
}

sub write {
    ${+shift}->write(@_) or JasPerl::IOException->throw($!);
}

1;
